package com.itheima.web.interceptor;

import cn.hutool.core.util.StrUtil;
import com.itheima.domain.db.Admin;
import com.itheima.web.adminmanager.AdminManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    private AdminManager adminManager;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        // 1.获取token
        String token = request.getHeader("Authorization");
        if (StrUtil.isEmpty(token)) {
            response.setStatus(401); // 拦截
            return false;
        }

        // 2.解析token
        Admin admin = adminManager.findUserByToken(token);
        if (admin == null) {
            response.setStatus(401); // 拦截
            return false;
        }

        // 3.将user存储到线程内
        AdminHolder.set(admin);

        // 4.放行
        return true;
    }


    // 最终处理
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AdminHolder.remove();
    }

}
